// server.js

const http = require("http");
const fs = require("fs");
const path = require("path");

const MIME_TYPES = {
  ".html": "text/html",
  ".css": "text/css",
  ".js": "text/javascript",
  ".json": "application/json",
  ".png": "image/png",
  ".jpg": "image/jpeg",
  ".gif": "image/gif",
  ".ico": "image/x-icon"
};

const server = http.createServer((req, res) => {
  // 对请求路径进行 decodeURIComponent 解码
  const decodedUrl = decodeURIComponent(req.url);

    let filePath;

    if (decodedUrl === "/") {
      filePath = path.join(__dirname,
    "index.html");
  } else if (decodedUrl.startsWith("/models/")) {
    // 处理 models 路径下的所有文件请求
      const relativePath = decodedUrl.substring(1); // 去掉开头的斜杠
      filePath = path.join(__dirname, relativePath);
  } else {
      filePath = path.join(__dirname, decodedUrl);
  }
  // 获取文件扩展名
    const extname = path.extname(filePath).toLowerCase();
    const contentType = MIME_TYPES[extname
  ] || "application/octet-stream";

    fs.readFile(filePath, (err, content) => {
        if (err) {
            if (err.code === "ENOENT") {
        // 文件不存在
                res.writeHead(404,
        {
          "Content-Type": "text/plain"
        });
                res.end("404 Not Found");
      } else {
        // 其他错误
                res.writeHead(500,
        {
          "Content-Type": "text/plain"
        });
                res.end("500 Internal Server Error");
      }
    } else {
      // 成功返回文件
            res.writeHead(200,
      {
        "Content-Type": contentType,
        "Content-Length": content.length // 设置正确的文件大小
      });
            res.end(content,
      "utf-8");
    }
  });
});

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running at http: //localhost:${PORT}/`);
});